<template>
  <!-- 导航 -->
  <el-row style="margin: 10px;background-color: ghostwhite;padding: 15px">
    <el-col :span="24">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
        <el-breadcrumb-item>主数据</el-breadcrumb-item>
        <el-breadcrumb-item>物料产品管理</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
  </el-row>

  <el-row style="margin: 10px">
    <el-col :span="3.5" style="margin-top: 10px">
      <!-- 树列表 -->
      <el-input
          v-model="filterText"
          style="width: 200px"
          placeholder="筛选关键词"
          :prefix-icon="Search"
          clearable/>

      <el-tree
          ref="treeRef"
          style="max-width: 200px;margin-top: 20px"
          class="filter-tree"
          :data="classifys"
          :props="{children: 'children',label: 'classifyName'}"
          default-expand-all
          :filter-node-method="filterNode"
          :expand-on-click-node="false"
          @node-click="classifySelect"
          @node-expand="handleNodeExpand"
          @node-collapse="handleNodeCollapse"/>
    </el-col>
    <el-col :span="20" style="margin-top: 5px">
      <!-- 搜索栏-->
      <el-row style="padding: 5px;margin-left: 15px">
        <el-col :span="24">
          <el-form :model="materialQuery" inline>
            <el-form-item label="物料编码">
              <el-input v-model="materialQuery.materialCode" clearable/>
            </el-form-item>

            <el-form-item label="物料名称">
              <el-input v-model="materialQuery.materialName" clearable/>
            </el-form-item>

            <el-form-item>
              <el-button @click="loadMaterials" type="primary"> <el-icon><Search /></el-icon>&nbsp搜索</el-button>
              <el-button @click="referMaterials"> <el-icon><Refresh /></el-icon>&nbsp重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <!-- 工具栏 -->
      <el-row style="margin: 0px 10px;padding: 0px 10px">
        <el-col :span="24">
          <el-button @click="toAddMaterial" type="primary" plain><el-icon><Plus /></el-icon>新增</el-button>
          <el-button @click="toEdits" type="success" plain><el-icon><EditPen /></el-icon>修改</el-button>
          <el-button @click="toDeletes" type="danger" plain><el-icon><Delete /></el-icon>删除</el-button>
        </el-col>
      </el-row>

      <!-- 数据列表 -->
      <el-row style="margin: 10px 5px;padding:0px 15px;">
        <el-col :span="24">
          <el-table :data="materials" border stripe ref="materialTable">
            <el-table-column type="selection" width="55"/>
            <el-table-column prop="materialCode" width="150px" label="物料编码">
              <template #default="scope">
                <el-link @click="showDetail(scope.row.materialId)" type="success">
                  {{ scope.row.materialCode }}</el-link>
              </template>
            </el-table-column>
            <el-table-column prop="materialName" width="120px" label="物料名称"/>
            <el-table-column prop="specification" width="120px" label="规格型号"/>
            <el-table-column prop="materialUnitCode" width="100px" label="单位"/>
            <el-table-column prop="kindType" width="100px" label="物料/产品">
              <template #default="scope">
                <el-tag type="success" v-if="scope.row.kindType == 1">物料</el-tag>
                <el-tag type="danger" v-if="scope.row.kindType == 2">产品</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="kindName" width="100px" label="所属分类"/>
            <el-table-column prop="materialStatus" width="100px" label="是否启用">
              <template #default="scope">
                <el-tag type="success" v-if="scope.row.materialStatus == 1">是</el-tag>
                <el-tag type="danger" v-if="scope.row.materialStatus == 2">否</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="safeFlag" width="120px" label="设置安全库存">
              <template #default="scope">
                <el-tag type="success" v-if="scope.row.safeFlag == 1">是</el-tag>
                <el-tag type="danger" v-if="scope.row.safeFlag == 2">否</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" width="120px" label="创建时间"/>

            <el-table-column label="操作" width="150px">
              <template #default="scope">
                <el-link @click="toEditMaterial(scope.row.materialId)" style="margin: 0px 5px" type="primary"><el-icon><EditPen /></el-icon>修改</el-link>
                <el-popconfirm width="200"
                               confirm-button-text="必须删"
                               cancel-button-text="点错了"
                               @confirm="deleteMaterialById(scope.row.materialId)"
                               title="您确定要删除这条数据吗？">
                  <template  #reference>
                    <el-link style="margin: 0px 5px" type="primary">
                      <el-icon><Delete /></el-icon>删除
                    </el-link>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <el-footer>
        <!--  分页栏 -->
        <el-row :span="5" style="margin-left: 800px">
          <el-col :span="1.5" style="color: dimgray;padding: 10px;margin-top: 5px">
            共 {{total}} 条
          </el-col>
          <el-col :span="2" style="padding: 10px">
            <el-pagination @change="changePage" background layout="prev, pager, next" :total="total"/>
          </el-col>
        </el-row>
      </el-footer>
    </el-col>
  </el-row>

  <!-- 新增弹窗组件 -->
  <materialAdd @cancelMaterialAdd="cancelMaterialAdd"
           @add-complete="addMaterialComplete"
           :is-show="addWinIsShow"
           style="margin-top: 100px"/>

  <!-- 编辑弹窗组件 -->
  <materialEdit :material-id="editMaterialId"
            @cancel-material-edit="cancelMaterialEdit"
            @edit-complete="editComplete"
            style="margin-top: 30px"/>
  <!-- 详情子组件 -->
  <materialDetail :material-id="detailMaterialId"
                  @cancel-material-detail="cancelMaterialDetail"
                  style="margin-top: 30px"/>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue';
import {Search} from '@element-plus/icons-vue';
import {ElTree} from "element-plus";
import classifyRequest from "@/api/classify.js";
import materialRequest from "@/api/material.js";
import {ElMessage} from "element-plus";
import {ElMessageBox} from 'element-plus'
import materialAdd from "@/views/md/material/material-add.vue";
import materialEdit from "@/views/md/material/material-edit.vue";
import materialDetail from "@/views/md/material/material-detail.vue";
// 封装搜索条件
let materialQuery = ref({});
// 定义数组保存所有物料信息
let materials = ref([]);
// 定义数组保存所有分类信息
let classifys = ref([]);
// 左半边查询
let filterText = ref('')
let treeRef = ref(null) // 移除了类型注解
// 总条数，默认0
let total = ref(0);
// 当前页码，默认1
let curPage = ref(1);
// 查询结果
let materialTable = ref(null);

const filterNode = (value, data) => { // 移除了类型注解
  if (!value) return true
  return data.classifyName.includes(value)
}

function handleNodeExpand(node, nodeComponent, e) {
  // 检查点击的元素是否是展开/折叠图标
  let target = e.target;
  while (target && target !== nodeComponent.$el) {
    if (target.classList.contains('el-tree-node__expand-icon')) {
      node.expanded = true;
      return;
    }
    target = target.parentNode;
  }
}

function handleNodeCollapse(node, nodeComponent, e) {
  // 检查点击的元素是否是展开/折叠图标
  let target = e.target;
  while (target && target !== nodeComponent.$el) {
    if (target.classList.contains('el-tree-node__expand-icon')) {
      node.expanded = false;
      return;
    }
    target = target.parentNode;
  }
}

/**
 * 菜单激活事件
 * @param data 选中节点的数据
 * @param node 选中节点的 Node 对象
 */
function classifySelect(data) {
  let kindIds = ref([]);
  // 递归函数来处理节点及其子节点
  function processClassifies(classifies) {
    classifies.forEach(classify => {
      // 将当前节点的 classifyId 添加到 kindIds 数组
      kindIds.value.push(classify.classifyId);
      // 如果当前节点有子节点，递归处理子节点
      if (classify.children && classify.children.length > 0) {
        processClassifies(classify.children);
      }
    });
  }
  // 将当前点击的 classifyId 添加到 kindIds 数组
  kindIds.value.push(data.classifyId);
  // 发送请求获取树形数据
  classifyRequest.getTree(data.classifyId, res => {
    // 确保 res.data 不是 null 或 undefined
    if (res && res.data) {
      // 使用递归函数处理获取到的分类数据
      processClassifies(res.data);
    }
    // 将数组赋值给查询条件中的 classify
    materialQuery.value.classify = kindIds.value;
    // 调用 loadMaterials 函数
    loadMaterials();
  });
}

/**
 * 加载物料列表
 */
function loadMaterials() {
  // 调用API来查询项目列表
  materialRequest.loadMaterials(materialQuery.value, curPage.value, 10, res => {
    // 这里的res就是后端返回的结果
    // 总条数赋值
    total.value = res.data.total;
    // 将查询的列表赋值给projects
    materials.value = res.data.list;
  })
}

/**
 * 重置按钮事件
 */
function referMaterials(){
  materialQuery.value.materialCode = null;
  materialQuery.value.materialName = null;
  loadMaterials();
}

// 分页事件
function changePage(value) {
  curPage.value = value;
  loadMaterials();
}

//新增窗口
let addWinIsShow = ref(false);

/**
 * 工具栏新增单位事件
 * @param material
 */
function toAddMaterial(material){
  loadMaterials();
  addWinIsShow.value = true;
}

/**
 * 新增物料完成的监听事件
 */
function addMaterialComplete(){
  cancelMaterialAdd();
  loadMaterials();
}

/**
 * 取消新增的事件
 */
function cancelMaterialAdd(){
  addWinIsShow.value = false;
  loadMaterials();
}

/**
 * 工具栏编辑按钮事件
 */
function toEdits(){
  let selectedRows = materialTable.value.getSelectionRows();
  if(selectedRows.length > 1){
    ElMessage({
      type:"warning",
      message:"编辑只能编辑一条数据"
    });
  }else if (selectedRows.length == 0){
    ElMessage({
      type:"warning",
      message:"你没有选中任何数据"
    });
  }else{
    toEditMaterial(selectedRows[0].materialId);
  }
}

/**
 * 工具栏批量删除按钮事件
 */
function toDeletes(){
  let selectedRows = materialTable.value.getSelectionRows();
  if (selectedRows.length == 0){
    ElMessage({
      type:"warning",
      message:"你没有选中任何数据"
    });
    return;
  }
  ElMessageBox.confirm(
      '您确定要删除选中的项目吗？',
      'Warning',
      {
        confirmButtonText: '是的',
        cancelButtonText: '点错了',
        type: 'warning',
      }
  ).then(() => {
    let materialIds = [];
    selectedRows.forEach(row=>{
      materialIds.push(row.materialId);
    })

    materialRequest.deletesMaterial(materialIds,res=>{
      if(res.code == 200){
        ElMessage({
          type:"success",
          message:"成功删除[" + res.data + "]条数据"
        })
        loadMaterials();
      }else{
        ElMessage({
          type:"warning",
          message:"删除失败"
        })
      }
    });
  }).catch(()=>{});
}

// 当前要编辑的分类的编号，默认是-1
let editMaterialId = ref(-1);

/**
 * 行级编辑按钮事件
 * @param material
 */
function toEditMaterial(materialId){
  editMaterialId.value = materialId;
}

/**
 * 编辑完成的事件
 */
function editComplete(){
  // 更新数据表
  cancelMaterialEdit();
  loadMaterials();
}

/**
 * 编辑取消的事件
 */
function cancelMaterialEdit(){
  // 将editClassifyId修改为-1
  editMaterialId.value = -1;
}

/**
 * 行删除按钮事件
 * @param materialId
 */
function deleteMaterialById(materialId) {
  materialRequest.deleteMaterialById(materialId,res => {
    if (res.code === 200) {
      ElMessage.success('删除完成');
      loadMaterials();
    }
  });
}

// 详情的 materialId
let detailMaterialId = ref(-1);

/**
 * 行详情页面按钮事件
 * @param materialId
 */
function showDetail(materialId) {
  detailMaterialId.value = materialId;
}

/**
 * 详情取消的事件
 */
function cancelMaterialDetail(){
  // 将detailMaterialId修改为-1
  detailMaterialId.value = -1;
  loadMaterials();
}

onMounted(() => {
  // 加载物料对象
  loadMaterials();
  // 加载分类对象
  classifyRequest.getTree(0,res=>{
    classifys.value = res.data;
  })
})

watch(filterText, (val) => {
  if (treeRef.value) {
    treeRef.value.filter(val)
  }
})
</script>

<style scoped>

</style>